import { Button, Input } from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import type { CustomReportParam } from "./entity";
import { useState } from "react";
import { toast } from "sonner";

interface ReportParamProps {
	loading: boolean;
	paramList: CustomReportParam[];
	setParamList: React.Dispatch<React.SetStateAction<CustomReportParam[]>>;
}

const CustomReportParamPage: React.FC<ReportParamProps> = ({ loading, paramList, setParamList }) => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  // 检查 paramName 是否已存在
  const isParamNameExist = (name: string) => {
    return paramList.some((param) => param.paramName === name);
  };

	const getFieldColumns = (
		handleFieldChange: (id: React.Key, field: string, value: any) => void,
	): ColumnsType<CustomReportParam> => [
		{
			title: "参数名",
			key: "paramName",
			dataIndex: "paramName",
			render: (text, record) => (
				<Input 
          value={text} 
          onChange={(e) => {
            const newValue = e.target.value.trim(); // 去除首尾空格
            // if (!newValue) {
            //   toast.error("参数名不能为空");
            //   return;
            // }
            if (isParamNameExist(newValue) && newValue !== record.paramName) {
              toast.error("参数名已存在");
              return;
            }
            handleFieldChange(record.id, "paramName", newValue);
          }}
          placeholder="请输入参数名（必填）"
        />
			),
		},
		{
			title: "参数描述",
			key: "paramComment",
			dataIndex: "paramComment",
			render: (text, record) => (
        <Input
          allowClear
          value={text}
          onChange={(e) => handleFieldChange(record.id, "paramComment", e.target.value)}
          placeholder="请输入参数描述"
        />
      ),
		},
		{
			title: "默认值",
			key: "defaultValue",
			dataIndex: "defaultValue",
			render: (text, record) => (
        <Input
          allowClear
          value={text}
          onChange={(e) => handleFieldChange(record.id, "defaultValue", e.target.value)}
          placeholder="请输入默认值"
        />
      ),
		},
	];

	// 处理字段变更
	const handleFieldChange = (id: React.Key, field: string, value: any) => {
    if (field === "paramName" && !value.trim()) {
      toast.error("参数名不能为空");
      return;
    }
		setParamList((prevData) => prevData.map((item) => (item.id === id ? { ...item, [field]: value } : item)));
	};

	// 获取字段列配置
	const fieldColumns = getFieldColumns(handleFieldChange);

  // 新增参数（校验 paramName 非空且唯一）
  const handleAdd = () => {
    // 生成一个不重复的临时参数名（如 param_1, param_2...）
    let newParamName = "";
    let index = 1;
    do {
      newParamName = `param_${index}`;
      index++;
    } while (isParamNameExist(newParamName));

    const newParam: CustomReportParam = {
      id: Date.now().toString(), // 临时唯一 ID
      paramName: newParamName, // 默认非空且唯一
      paramComment: "",
      defaultValue: "",
    };

    setParamList((prevParams) => [...prevParams, newParam]);
  };

  const handleDelete = async () => {
    if (selectedRowKeys.length === 0) {
      toast.warning("请至少选择一行数据");
      return;
    }
    setParamList((prevList) =>
      prevList.filter((item) => !selectedRowKeys.includes(item.id))
    );
    setSelectedRowKeys([]);
    toast.success("删除成功");
  };

	return (
		<>
			<div className="flex justify-between mb-4">
				<div className="flex gap-2">
					<Button type="primary" onClick={handleAdd}>
						新增
					</Button>
					<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
						删除
					</Button>
				</div>
			</div>
			<Table
				rowKey="id"
        size="small"
				loading={loading}
				pagination={false}
				columns={fieldColumns}
				dataSource={paramList}
				scroll={{
					y: 200, // 固定高度，触发垂直滚动
				}}
        rowSelection={{
          type: "checkbox",
          selectedRowKeys: selectedRowKeys,
          onChange: (selectedKeys) => {
            setSelectedRowKeys(selectedKeys as string[]);
          },
        }}
			/>
		</>
	);
};

export default CustomReportParamPage;
